import math

from controllers.Base import HttpController, g_xcmsDict
import json
from utils.Utils import xc_gen_random_code
from settings import g_settings

# 查询所有xcms节点接口 （支持关键词模糊）
class XcmsListController(HttpController):

    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        data = []
        page_data = {
        }

        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()

        if safe == g_settings.appKey + g_settings.appSecret:
            try:
                page = int(request_params.get("page",1))
                page_size = int(request_params.get("page_size",10))
                if page < 1:
                    raise Exception("the page cannot be less than 1")
                if page_size < 10:
                    raise Exception("the page_size cannot be less than 10")

                total_data = []
                name = request_params.get('name',"").strip() # 模糊搜索xcms的关键词
                describe = request_params.get('describe',"").strip() # 模糊搜索xcms的关键词

                if len(g_xcmsDict) > 0:

                    xcms_list = g_xcmsDict.values()

                    if name!="" and describe!="":
                        for v in xcms_list:
                            xcms_name = v["xcms_name"]
                            xcms_describe = v["xcms_describe"]
                            if name in xcms_name and describe in xcms_describe:
                                total_data.append({
                                    "timestamp": v["timestamp"],
                                    "date": v["date"],
                                    "xcms_name": xcms_name,
                                    "xcms_describe": xcms_describe,
                                    "xcms_version": v["xcms_version"],
                                    "xcms_flag": v["xcms_flag"],
                                    "xcms_systemName": v["xcms_systemName"],
                                    "xcms_machineNode": v["xcms_machineNode"],
                                    "xcms_host": v["xcms_host"],
                                    "state": 1 # 0:离线 1:在线
                                })
                    elif name!="" and describe=="":
                        for v in xcms_list:
                            xcms_name = v["xcms_name"]
                            xcms_describe = v["xcms_describe"]
                            if name in xcms_name:
                                total_data.append({
                                    "timestamp": v["timestamp"],
                                    "date": v["date"],
                                    "xcms_name": xcms_name,
                                    "xcms_describe": xcms_describe,
                                    "xcms_version": v["xcms_version"],
                                    "xcms_flag": v["xcms_flag"],
                                    "xcms_systemName": v["xcms_systemName"],
                                    "xcms_machineNode": v["xcms_machineNode"],
                                    "xcms_host": v["xcms_host"],
                                    "state": 1 # 0:离线 1:在线
                                })
                    elif name == "" and describe != "":
                        for v in xcms_list:
                            xcms_name = v["xcms_name"]
                            xcms_describe = v["xcms_describe"]
                            if describe in xcms_describe:
                                total_data.append({
                                    "timestamp": v["timestamp"],
                                    "date": v["date"],
                                    "xcms_name": xcms_name,
                                    "xcms_describe": xcms_describe,
                                    "xcms_version": v["xcms_version"],
                                    "xcms_flag": v["xcms_flag"],
                                    "xcms_systemName": v["xcms_systemName"],
                                    "xcms_machineNode": v["xcms_machineNode"],
                                    "xcms_host": v["xcms_host"],
                                    "state": 1 # 0:离线 1:在线
                                })
                    else:
                        for v in xcms_list:
                            xcms_name = v["xcms_name"]
                            xcms_describe = v["xcms_describe"]
                            total_data.append({
                                "timestamp": v["timestamp"],
                                "date": v["date"],
                                "xcms_name": xcms_name,
                                "xcms_describe": xcms_describe,
                                "xcms_version": v["xcms_version"],
                                "xcms_flag": v["xcms_flag"],
                                "xcms_systemName": v["xcms_systemName"],
                                "xcms_machineNode": v["xcms_machineNode"],
                                "xcms_host": v["xcms_host"],
                                "state": 1  # 0:离线 1:在线
                            })

                    total_count = len(total_data)
                    page_num = math.ceil(total_count / page_size) # 进一法
                    start = (page-1) * page_size
                    end = start + page_size
                    data = total_data[start:end]

                    page_data = {
                        "total_count": total_count,  # xcms节点总数量
                        "page_num": page_num,  # 总页数
                        "page": page,  # 当前页
                        "page_size": page_size,  # 页长
                    }

                    ret = True
                    msg = "success"
                else:
                    msg = "empty"
            except Exception as e:
                msg = str(e)
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "data": data,
            "page_data": page_data
        }
        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

# 根据指定xcms节点查询所有摄像头接口（支持关键词模糊）
class XcmsStreamListController(HttpController):
    async def get(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        info = {}
        request_params = self.request_get_params()
        safe = request_params.get('safe',"").strip()

        if safe == g_settings.appKey + g_settings.appSecret:
            xcms_name = request_params.get('xcms_name',"").strip() # xcms节点
            keyword = request_params.get('keyword',"").strip() # 模糊搜索摄像头的关键词

            val = g_xcmsDict.get(xcms_name)
            if val:
                try:
                    ws = val.get("ws")
                    message_type = "CmdXcmsStreamList"
                    message_uuid = xc_gen_random_code()
                    __cmd_data = {
                        "message_type": message_type,
                        "message_uuid": message_uuid,
                        "xcms_name": xcms_name,
                        "keyword": keyword
                    }
                    ws.send_cmd(__cmd_data)

                    info["message_type"] = message_type
                    info["message_uuid"] = message_uuid
                    ret = True
                    msg = "success"
                except Exception as e:
                    msg = "send error: %s" % str(e)
            else:
                msg = "The current xcms node does not exist"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "info": info
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

# 开启转发代理
class XcmsStreamAddProxyController(HttpController):
    async def post(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        info = {}
        request_params = self.request_post_params()
        safe = request_params.get('safe',"").strip()

        if safe == g_settings.appKey + g_settings.appSecret:
            xcms_name = request_params.get('xcms_name',"").strip() # xcms节点
            stream_code = request_params.get('stream_code',"").strip()

            val = g_xcmsDict.get(xcms_name)
            if val:
                try:
                    ws = val.get("ws")
                    message_type = "CmdXcmsStreamAddProxy"
                    message_uuid = xc_gen_random_code()
                    __cmd_data = {
                        "message_type": message_type,
                        "message_uuid": message_uuid,
                        "xcms_name": xcms_name,
                        "stream_code": stream_code
                    }
                    ws.send_cmd(__cmd_data)

                    info["message_type"] = message_type
                    info["message_uuid"] = message_uuid
                    ret = True
                    msg = "success"
                except Exception as e:
                    msg = "send error: %s" % str(e)
            else:
                msg = "The current xcms node does not exist"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "info": info
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

# 关闭转发代理
class XcmsStreamDelProxyController(HttpController):
    async def post(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        info = {}
        request_params = self.request_post_params()
        safe = request_params.get('safe',"").strip()

        if safe == g_settings.appKey + g_settings.appSecret:
            xcms_name = request_params.get('xcms_name',"").strip() # xcms节点
            stream_code = request_params.get('stream_code',"").strip()

            val = g_xcmsDict.get(xcms_name)
            if val:
                try:
                    ws = val.get("ws")
                    message_type = "CmdXcmsStreamDelProxy"
                    message_uuid = xc_gen_random_code()
                    __cmd_data = {
                        "message_type": message_type,
                        "message_uuid": message_uuid,
                        "xcms_name": xcms_name,
                        "stream_code": stream_code
                    }
                    ws.send_cmd(__cmd_data)

                    info["message_type"] = message_type
                    info["message_uuid"] = message_uuid
                    ret = True
                    msg = "success"
                except Exception as e:
                    msg = "send error: %s" % str(e)
            else:
                msg = "The current xcms node does not exist"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "info": info
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)

# ptz
class XcmsStreamPtzController(HttpController):
    async def post(self, *args, **kwargs):
        data = await self.do()
        self.write(data)

    async def do(self):
        ret = False
        msg = "unknown error"
        info = {}
        request_params = self.request_post_params()
        safe = request_params.get('safe',"").strip()

        if safe == g_settings.appKey + g_settings.appSecret:
            xcms_name = request_params.get('xcms_name',"").strip() # xcms节点
            stream_code = request_params.get('stream_code',"").strip()
            ptzType = int(request_params.get("ptzType", 0))
            val = int(request_params.get("val", 0))

            xcms_val = g_xcmsDict.get(xcms_name)
            if xcms_val:
                try:
                    ws = xcms_val.get("ws")
                    message_type = "CmdXcmsStreamPtz"
                    message_uuid = xc_gen_random_code()
                    __cmd_data = {
                        "message_type": message_type,
                        "message_uuid": message_uuid,
                        "xcms_name": xcms_name,
                        "stream_code": stream_code,
                        "ptzType": ptzType,
                        "val": val
                    }
                    ws.send_cmd(__cmd_data)

                    info["message_type"] = message_type
                    info["message_uuid"] = message_uuid
                    ret = True
                    msg = "success"
                except Exception as e:
                    msg = "send error: %s" % str(e)
            else:
                msg = "The current xcms node does not exist"
        else:
            msg = "unsafe"

        res = {
            "code": 1000 if ret else 0,
            "msg": msg,
            "info": info
        }

        return json.dumps(res)
        # return json.dumps(data, cls=ComplexEncoder)